/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.edu.iuh.dhth7dlt.emailclient.utils;

import java.io.IOException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.codec.binary.Base64;

/**
 *
 * @author Friendless
 */
public class SMTP {
    private boolean  isOK=true;
    public String sendmail(HashMap<String, String> params) throws IOException, EmailExceptions {
        try {
            String to = params.get("to");
            String from = params.get("from");
            String body = params.get("body");
            String name = params.get("name");
            String username = params.get("username");
            String pass = params.get("pass");
            String cc = params.get("cc");
            String bcc = params.get("bcc");
            String subject = params.get("subject");
            String server = params.get("smtp");
            int port = Integer.parseInt(params.get("port"));
            String pathDB = params.get("pathDB");
            String response;
            String code;
            String message = "";

            //Khởi tạo socket
            TCP tcp = new TCP(server, port);

            // Mã hóa user password sang base64
            Base64 codec = new Base64();
            String user = base64_encode(username);
            String password = base64_encode(pass);

            //Gửi lời chào
            response = tcp.request("EHLO dhth7dlt.com");
            code = split_response(response)[0];
            System.out.println(code);

            //Chức thực
            response = tcp.request("AUTH LOGIN " + user);
            code = split_response(response)[0];
            if (!"334".equals(code)) {
                isOK=false;
                throw new EmailExceptions().set_error("Lỗi username");
            }

            //Gửi password mã hóa
            response = tcp.request(password);
            code = split_response(response)[0];
            if (!code.equals("235")) {
                isOK=false;
                throw new EmailExceptions().set_error("Lỗi password");
            }
            if (!from.isEmpty()) {
                //Mail người gửi
                response = tcp.request("MAIL FROM:" + from);
                code = split_response(response)[0];
                if (!code.equals("250")) {
                    throw new EmailExceptions().set_error("Lỗi email người gửi");
                }
                String listEmailTo = EmailAddress.getEmails(to);
                String listEmailCC = EmailAddress.getEmails(cc);
                String listEmailBCC = EmailAddress.getEmails(bcc);
                String listSendTo = "";
                listSendTo = listEmailTo.length() > 0 ? listSendTo += listEmailTo : "";
                listSendTo = listSendTo.length() > 0 ? listSendTo += "," + listEmailCC : listEmailCC;
                listSendTo = listSendTo.length() > 0 ? listSendTo += "," + listEmailBCC : listEmailBCC;

                String[] arrayListSendTo = listSendTo.split(",");
                for (int i = 0; i < arrayListSendTo.length; i++) {
                    response = tcp.request("RCPT TO:" + arrayListSendTo[i]);
                    code = split_response(response)[0];
                    if(code.endsWith("550"))
                        throw new EmailExceptions().set_error("Email này không tồn tại" + arrayListSendTo[i]);
                    if (!code.equals("250")) {
                        throw new EmailExceptions().set_error("Lỗi email người nhận" + arrayListSendTo[i]);
                    }
                }

                //header
                response = tcp.request("DATA");
                code = split_response(response)[0];
                if (!code.equals("354")) {
                    throw new EmailExceptions().set_error("Lỗi không gửi được \"Data\"");
                }
                DateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
                Date date = new Date();
                message += "From:" + name + "<" + from + ">\n";
                message += "To:" + listEmailTo + "\n";
                message += "CC:" + listEmailCC + "\n";
                message += "Date:" + dateFormat.format(date) + "\n";
                message += "Subject:" + subject + "\r\n\n";
                message += body;

                System.out.println(message);

                //body
                response = tcp.request(message + "\r\n.\r\n");
                code = split_response(response)[0];
                if (!code.equals("250")) {
                    throw new EmailExceptions().set_error("Không gửi được email");
                }
                SqliteHelper inHelper = new SqliteHelper(pathDB);
                inHelper.insertEmail(message);
                //Đóng kết nối
                tcp.close();

                return response;
            }
        } catch (ClassNotFoundException | SQLException ex) {
            Logger.getLogger(SMTP.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;

    }

    String[] split_response(String response) {
        return response.split(" ");
    }

    String base64_encode(String input) {
        return Base64.encodeBase64String(input.getBytes());
    }

    String base64_decode(String input) {
        return new String(Base64.decodeBase64(input));
    }
    public boolean isConfigOK()
    {
        return isOK;
    }
}
